package org.fire.client;

import com.google.protobuf.GeneratedMessage;

/**
 * 数据包
 * <p>
 * 
 * <pre>
 * +++++++++++++++++
 * 数据包结构
 * -----------------
 * 包长 | 包体
 * +++++++++++++++++
 * </pre>
 * 
 * 包体为空时校验和填0
 * 
 * @author lhl
 *
 */
public class Packet
{
	public static final short HEAD_SIZE = 2;
	private byte[] body;

	public Packet()
	{
	}

	public byte[] getBody()
	{
		return body;
	}

	public void setBody(byte[] body)
	{
		this.body = body;
	}

	public short getLength()
	{
		return (short) (body == null ? HEAD_SIZE : (HEAD_SIZE + body.length));
	}

	/**
	 * 将Packet对象解析为Protpbuf对象
	 * 
	 * @param pkt
	 * @param t
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T extends GeneratedMessage> T parse(Packet pkt, T t)
	{
		try
		{
			return (T) t.getDefaultInstanceForType().toBuilder().mergeFrom(pkt.getBody()).build();
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}
	}
}
